<script setup lang="ts">
import { inject, onMounted, ref, watch } from 'vue'
import { useYklibLoginStore } from 'yklib'
import { throttle } from 'lodash-es'

const printToTerm = inject('printToTerm') as (text: string) => void
const setTaskBar = inject('setTaskBar') as (text: string, progress?: number) => void
const store = useYklibLoginStore()

const deployStatus = ref({
  mysql: { status: '', message: '' },
  caddy: { status: '', message: '' },
  nextcloud: { status: '', message: '' },
  registry: { status: '', message: '' },
  loginReg: { status: '', message: '' }
})

const server_domain = ref('hs.yangke.site')
const selectedFolder = ref('')
const mysql_port = ref('3306') // 不会实时修改，需要watch后保存到projectSettings才能实时修改
const mysql_root_password = ref('YangKe.08')
const nextcloud_port = ref('20002')  // 新增：Nextcloud服务端口
const nextcloud_version = ref('31')  // 新增：Nextcloud版本
const nextcloud_use_caddy = ref(true) // 是否用caddy代理https链接
const registry_server_port = ref('10004') // Docker Registry Hub服务端口，命令行上传镜像使用
const registry_browser_port = ref('20005') // docker-registry-browser页面访问端口
const login_reg_port = ref('5001')

const deployAll = async () => {
  try {
    setTaskBar('开始一键部署...', 10)
    // 一键部署，必须先安装docker镜像，再启动容器，因为默认从docker-compose.yml中启动时使用不了docker镜像
    await deployMySQL()
    await deployCaddy()
    await deployNextcloud()
    setTaskBar('一键部署完成', 100)
  } catch (error) {
    printToTerm(`部署失败: ${error}`)
    setTaskBar('一键部署失败', 0)
  }
}

const deployMySQL = async () => {
  try {
    deployStatus.value.mysql.status = '部署中...'
    setTaskBar('正在部署MySQL...', 30)
    // @ts-ignore
    const result = await window.pywebview.api.deployMySQL({
      image: 'mysql:latest',
      name: 'mysql',
      mysql_root_password: mysql_root_password.value,
      mysql_port: mysql_port.value
    })

    if (result.suc) {
      deployStatus.value.mysql = { status: '✓ 已部署', message: result.msg }
    } else {
      deployStatus.value.mysql = { status: '✗ 失败', message: result.msg }
    }
  } catch (error) {
    deployStatus.value.mysql = { status: '✗ 错误', message: error.message }
  }
}

const deployCaddy = async () => {
  try {
    if (!selectedFolder.value) {
      deployStatus.value.caddy = { status: '✗ 失败', message: '请选择要部署的文件夹' }
      return
    }

    deployStatus.value.caddy.status = '部署中...'
    setTaskBar('正在部署Caddy...', 60)
    // @ts-ignore
    const result = await window.pywebview.api.deployCaddy({
      image: 'caddy:latest',
      name: 'caddy',
      siteFolder: selectedFolder.value,
      server_domain: server_domain.value
    })

    if (result.suc) {
      deployStatus.value.caddy = { status: '✓ 已部署', message: result.msg }
    } else {
      deployStatus.value.caddy = { status: '✗ 失败', message: result.msg }
    }
  } catch (error) {
    deployStatus.value.caddy = { status: '✗ 错误', message: error.message }
  }
}

const deployNextcloud = async () => {
  try {
    deployStatus.value.nextcloud.status = '部署中...'
    setTaskBar('正在部署Nextcloud...', 80)
    // @ts-ignore
    const result = await window.pywebview.api.deployNextcloud({
      nextcloud_version: nextcloud_version.value,
      nextcloud_port: nextcloud_port.value,
      nextcloud_use_caddy: nextcloud_use_caddy.value,
      server_domain: server_domain.value,
      mysql_root_password: mysql_root_password.value
    })

    if (result.suc) {
      deployStatus.value.nextcloud = { status: '✓ 已部署', message: result.msg }
    } else {
      deployStatus.value.nextcloud = { status: '✗ 失败', message: result.msg }
    }
  } catch (error) {
    deployStatus.value.nextcloud = { status: '✗ 错误', message: error.message }
  }
}
const deployDockerRegistryHub = async () => {
  try {
    deployStatus.value.registry.status = '部署中...'
    setTaskBar('正在部署Docker私有镜像仓库...', 80)
    // @ts-ignore
    const result = await window.pywebview.api.deployDockerRegistryHub({
      caddy_container_name: 'caddy_container',
      registry_server_port: registry_server_port.value,
      registry_browser_port: registry_browser_port.value,
      server_domain: server_domain.value
    })

    if (result.suc) {
      deployStatus.value.registry = { status: '✓ 已部署', message: result.msg }
    } else {
      deployStatus.value.registry = { status: '✗ 失败', message: result.msg }
    }
  } catch (error) {
    deployStatus.value.registry = { status: '✗ 错误', message: error.message }
  }
}
const deployLoginRegService = async () => {
  try {
    deployStatus.value.loginReg.status = '部署中...'
    setTaskBar('正在部署Docker私有镜像仓库...', 80)
    // @ts-ignore
    const result = await window.pywebview.api.deployLoginRegService({
      caddy_container_name: 'caddy_container',
      login_reg_port: login_reg_port.value,
      mysql_host: 'localhost',
      mysql_port: mysql_port.value,
      mysql_root_password: mysql_root_password.value,

      server_domain: server_domain.value
    })

    if (result.suc) {
      deployStatus.value.loginReg = { status: '✓ 已部署', message: result.msg }
    } else {
      deployStatus.value.loginReg = { status: '✗ 失败', message: result.msg }
    }
  } catch (error) {
    deployStatus.value.loginReg = { status: '✗ 错误', message: error.message }
  }
}
const selectSiteFolder = async () => {
  try {
    // @ts-ignore
    selectedFolder.value = await window.pywebview.api.selectedFolder()
  } catch (error) {
    console.log('选择文件夹失败', error)
    selectedFolder.value = selectedFolder.value || ''
  }
}


watch(
  [() => selectedFolder.value, () => mysql_port.value, () => mysql_root_password.value,
    () => nextcloud_port.value, () => nextcloud_version.value, () => nextcloud_use_caddy.value,
    () => server_domain.value, () => registry_server_port.value, () => registry_browser_port.value,
    () => login_reg_port.value, () => deployStatus.value],
  throttle(
    ([newFolder, newPort, newPassword, newNPort, newVersion, newUseCaddy, newDomain,
       newRegistryPort, newRegistryBrowserPort, newLoginRegPort, newDeployStatus]) => {
      store.saveProjectSettings({
        'QuickDeploy': {
          selectedFolder: newFolder,
          mysql_port: newPort,
          mysql_root_password: newPassword,
          nextcloud_port: newNPort,
          nextcloud_version: newVersion,
          nextcloud_use_caddy: newUseCaddy,
          server_domain: newDomain,
          registry_server_port: newRegistryPort,
          registry_browser_port: newRegistryBrowserPort,
          login_reg_port: newLoginRegPort,
          deployStatus: newDeployStatus
        }
      })
    }, 1000, { leading: true, trailing: true })
)

onMounted(async () => {
  const settings = await store.loadProjectSettings('QuickDeploy')
  if (settings) {
    selectedFolder.value = settings.selectedFolder
    mysql_port.value = settings.mysql_port || '3306'
    mysql_root_password.value = settings.mysql_root_password || 'YangKe.08'
    nextcloud_port.value = settings.nextcloud_port || '20002'
    nextcloud_version.value = settings.nextcloud_version || '31'
    nextcloud_use_caddy.value = settings.nextcloud_use_caddy || true
    server_domain.value = settings.server_domain || ''
    registry_browser_port.value = settings.registry_browser_port || '20005'
    registry_server_port.value = settings.registry_server_port || '10004'
    login_reg_port.value = settings.login_reg_port || '5001'
    deployStatus.value = settings.deployStatus || {
      mysql: { status: '', message: '' },
      caddy: { status: '', message: '' },
      nextcloud: { status: '', message: '' },
      registry: { status: '', message: '' },
      loginReg: { status: '', message: '' }
    }
  }
})


</script>

<template>
  <div class="space-y-4">
    <button @click="deployAll" class="bg-green-500 text-white py-2 px-4 rounded-lg shadow-md hover:bg-green-600">
      一键部署全部
    </button>
    <div class="mt-4">
      <label for="server_domain" class="block text-sm font-medium text-gray-700">服务器域名</label>
      <input
        id="server_domain"
        v-model="server_domain"
        type="text"
        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
        placeholder="例如：example.com"
      />
    </div>

    <div class="grid grid-cols-1 gap-4">
      <div class="bg-white p-4 rounded-lg shadow">
        <h3 class="font-medium">MySQL</h3>


        <!-- 添加以下输入项 -->
        <div class="mt-3 space-y-2">
          <div>
            <label class="block text-sm font-medium text-gray-700">MySQL 端口</label>
            <input v-model="mysql_port" type="text"
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="例如：3306">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">MySQL Root 密码</label>
            <input v-model="mysql_root_password" type="password"
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="请输入密码">
          </div>
        </div>
        <div class="flex justify-between items-center mt-2">
          <span>{{ deployStatus.mysql.status }}</span>
          <button @click="deployMySQL" class="bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
            单独部署
          </button>
        </div>

        <p class="text-sm text-gray-500 mt-1">{{ deployStatus.mysql.message }} 服务地址：
          <a :href="`https://${server_domain}:${mysql_port}`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">{{ server_domain }}:{{ mysql_port }}</a></p>
      </div>

      <div class="bg-white p-4 rounded-lg shadow">
        <h3 class="font-medium">Caddy</h3>
        <div class="mt-2">
          <div class="mb-2">
            <label class="mx-5">选择网站文件夹(index.html所在的文件夹)：</label>
            <label v-if="!selectedFolder" class="text-sm text-gray-500">未选择文件夹</label>
            <label v-else class="text-sm text-green-500">已选择: {{ selectedFolder }}</label>
            <button @click="selectSiteFolder"
                    class="mx-13 bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
              选择
            </button>
          </div>
          <div class="flex justify-between items-center">
            <span>{{ deployStatus.caddy.status }}</span>
            <button @click="deployCaddy" class="bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
              单独部署
            </button>
          </div>
        </div>

        <p class="text-sm text-gray-500 mt-1">{{ deployStatus.caddy.message }}
          <a :href="`https://${server_domain}`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">服务地址：{{ server_domain }}</a></p>
      </div>

      <div class="bg-white p-4 rounded-lg shadow">
        <h3 class="font-medium">Nextcloud</h3>
        <div class="mt-3 space-y-2">
          <div class="flex items-center mb-2">
            <input v-model="nextcloud_use_caddy" type="checkbox" id="use-docker" class="mr-2" />
            <label for="use-docker">使用 Caddy 代理https协议链接</label>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">服务端口</label>
            <input v-model="nextcloud_port" type="text"
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="例如：8080">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">Nextcloud版本</label>
            <select v-model="nextcloud_version"
                    class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
              <option value="latest">最新版</option>
              <option value="31" selected>31</option>
              <option value="30">30</option>
            </select>
          </div>
        </div>
        <div class="flex justify-between items-center mt-2">
          <span>{{ deployStatus.nextcloud.status }}</span>
          <button @click="deployNextcloud" class="bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
            单独部署
          </button>
        </div>

        <p class="text-sm text-gray-500 mt-1">{{ deployStatus.nextcloud.message }}
          <a :href="`https://${server_domain}:${nextcloud_port}`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">服务地址：{{ server_domain }}:{{ nextcloud_port }}</a></p>
      </div>

      <div class="bg-white p-4 rounded-lg shadow">
        <h3 class="font-medium">Docker私有仓库</h3>
        <div class="mt-2">
          <div class="mb-2">
            <span>必须先部署caddy</span>
          </div>
          <div class="mt-3 space-y-2">
            <div>
              <label class="block text-sm font-medium text-gray-700">Docker仓库端口</label>
              <input v-model="registry_server_port" type="text"
                     class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                     placeholder="例如：3306">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700">Docker仓库管理页面访问端口</label>
              <input v-model="registry_browser_port" type="text"
                     class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                     placeholder="例如：20004">
            </div>
          </div>
          <div class="flex justify-between items-center mt-2">
            <span>{{ deployStatus.registry.status }}</span>
            <button @click="deployDockerRegistryHub"
                    class="bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
              单独部署
            </button>
          </div>
        </div>

        <p class="text-sm text-gray-500 mt-1">{{ deployStatus.registry.message }}
          <a :href="`https://${server_domain}:${registry_browser_port}`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">服务地址：{{ server_domain }}:{{ registry_browser_port }}</a></p>
      </div>

      <div class="bg-white p-4 rounded-lg shadow">
        <h3 class="font-medium">登录注册服务</h3>
        <div class="mt-2">
          <div class="mb-2">
            <span>必须先部署MySQL</span>
          </div>
          <div class="mt-3 space-y-2">
            <div>
              <label class="block text-sm font-medium text-gray-700">服务端口</label>
              <input v-model="login_reg_port" type="text"
                     class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                     placeholder="例如：5001">
            </div>
          </div>
          <div class="flex justify-between items-center mt-2">
            <span>{{ deployStatus.loginReg.status }}</span>
            <button @click="deployLoginRegService"
                    class="bg-blue-500 text-white py-1 px-3 rounded text-sm hover:bg-blue-600">
              单独部署
            </button>
          </div>
        </div>
        <p class="text-sm text-gray-500 mt-1">{{ deployStatus.loginReg.message }}
          <a :href="`https://${server_domain}:${login_reg_port}`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">服务地址：{{ server_domain }}:{{ login_reg_port }}</a></p>
        <p class="text-sm text-gray-500 mt-1">测试注册服务后台数据库连接：<a :href="`https://${server_domain}:${login_reg_port}/?Action=GetPoolInfo`" target="_blank" class="text-blue-500
          hover:text-blue-700 hover:underline">服务地址：{{ server_domain }}:{{ login_reg_port }}/?Action=GetPoolInfo</a></p>
      </div>

    </div>
  </div>
</template>